<template>
  <div>
    <new-page ref="newPage" @update="refresh"></new-page>
    <div class="add-page" v-if="showEdit">
      <el-button type="primary" size="mini" @click="handleNewPage"
        >新增一级栏目
      </el-button>
    </div>

    <menu-item
      :menu="datas"
      :showEdit="showEdit"
      :currentExpandedId="currentExpandedId"
    ></menu-item>
  </div>
</template>

<script>
import NewPage from "./NewPage.vue";

import menuItem from "./menuItem.vue";
import { EventBus } from "@/EventBus";

export default {
  props: {
    showEdit: {
      default: false,
    },
  },
  components: {
    menuItem,
    NewPage,
  },
  data() {
    return {
      datas: [],
      currentExpandedId: null,
    };
  },

  mounted() {
    this.fetchData();
  },

  created() {
    EventBus.$on("expandItem", this.setCurrentExpandedId);
    EventBus.$on("menuRefresh", this.refresh);
  },
  beforeDestroy() {
    EventBus.$off("expandItem", this.setCurrentExpandedId);
    EventBus.$off("menuRefresh", this.refresh);
  },

  methods: {
    refresh() {
      this.fetchData();
    },
    async fetchData() {
      const loading = this.$loading();
      const { data } = await this.$fetch.get("/api/directory/list");
      this.datas = data;
      loading.close();
    },

    handleNewPage() {
      const { newPage } = this.$refs;
      return newPage && newPage.visible && newPage.visible();
    },
    setCurrentExpandedId(id) {
      this.currentExpandedId = id !== this.currentExpandedId ? id : null; // 点击同一个菜单项时收起
      this.$emit("select", id, this.currentExpandedId);
    },
  },
};
</script>

<style scoped>
::v-deep .el-button--mini {
  padding: 4px;
}

.add-page {
  margin-bottom: 20px;
  margin-top: 20px;
}
</style>
